package com.hzeport.bgs22emduty.xxljob;

import au.id.jericho.lib.html.CharacterReference;
import com.hzeport.bgs22emduty.client.HD12360Service;
import com.hzeport.bgs22emduty.client.HD12360ServiceSoap;
import com.hzeport.bgs22emduty.config.SystemConfig;
import com.hzeport.bgs22emduty.entity.SmsInfo;
import com.hzeport.bgs22emduty.outbound.SmsInfoRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.xml.ws.Holder;
import java.net.URL;
import java.time.LocalDateTime;

@Slf4j
@Component
public class MessageSendUtil {

    @Resource
    private SystemConfig systemConfig;

    @Resource
    private SmsInfoRepository wxpSmsInfoRepository;



    public void sendMessage(String phone, String msgContent) {
        //发送记录入库
        SmsInfo nfzxSmsLog = new SmsInfo();
        nfzxSmsLog.setSmsSendTime(LocalDateTime.now());
        nfzxSmsLog.setSmsContent(msgContent);
        nfzxSmsLog.setSmsReceive(phone);
        nfzxSmsLog.setCreateTime(LocalDateTime.now());
        nfzxSmsLog.setUpdateTime(LocalDateTime.now());
        nfzxSmsLog.setCreateBy("system");
        nfzxSmsLog.setUpdateBy("system");
        try {
            //地址清洗
            String auth_url = CharacterReference.decode( systemConfig.getMessageSendUrl() );
            HD12360Service proxy = new HD12360Service( new URL( auth_url ) );
            HD12360ServiceSoap hd12360ServiceSoap = proxy.getHD12360ServiceSoap();
            Holder<Integer> result = new Holder<>();
            Holder<String> errMsg = new Holder<>();
            hd12360ServiceSoap.submitSmsExact(systemConfig.getMessageaAppCode(),
                    msgContent, phone, null,
                    systemConfig.getExtensionCode(), systemConfig.getMPriority(),
                    systemConfig.getIsEncrypt(), systemConfig.getSmsSign(), result, errMsg);
            log.info("短信发送结果{},短信发送错误信息{}",result.value,errMsg.value);
            if (result.value != 0) {
                nfzxSmsLog.setSendStatus("2");
                log.error("发送失败,错误信息为" + errMsg.value);
            } else {
                nfzxSmsLog.setSendStatus("1");
            }
        } catch (Exception e) {
            nfzxSmsLog.setSendStatus("2");
            log.error("发送失败，原因为" + e);
        }
        wxpSmsInfoRepository.save(nfzxSmsLog);
    }
}
